import 'package:abc/view/default_empty_indicator.dart';
import 'package:abc/view/default_error_indicator.dart' show DefaultErrorIndicator;
import 'package:flutter/material.dart';

/// 分页视图类型
enum PaginationViewType {
  listView,
  gridView,
}

/// 网格布局配置
class PaginationGridConfig {
  /// 每行列数
  final int crossAxisCount;

  /// 子项宽高比
  final double childAspectRatio;

  /// 主轴间距
  final double mainAxisSpacing;

  /// 交叉轴间距
  final double crossAxisSpacing;

  /// 子项主轴扩展
  final double mainAxisExtent;

  const PaginationGridConfig({
    this.crossAxisCount = 2,
    this.childAspectRatio = 1.0,
    this.mainAxisSpacing = 8.0,
    this.crossAxisSpacing = 8.0,
    this.mainAxisExtent = 0.0,
  });

  /// 创建SliverGridDelegate
  SliverGridDelegate get gridDelegate {
    if (mainAxisExtent > 0) {
      return SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: crossAxisCount,
        mainAxisSpacing: mainAxisSpacing,
        crossAxisSpacing: crossAxisSpacing,
        childAspectRatio: childAspectRatio,
        mainAxisExtent: mainAxisExtent,
      );
    } else {
      return SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: crossAxisCount,
        mainAxisSpacing: mainAxisSpacing,
        crossAxisSpacing: crossAxisSpacing,
        childAspectRatio: childAspectRatio,
      );
    }
  }
}

/// 分页列表视图的抽象基类
abstract class PaginationListController<T> {
  /// 需要加载数据的方法
  /// [currentPage] 当前页码
  /// [pageSize] 每页大小
  /// [hasMore] 是否还有更多数据
  /// 返回Future<List<T>>，业务端在这里调用接口并返回数据列表
  Future<List<T>> loadDatas(int currentPage, int pageSize, bool hasMore);

  /// 判断是否还有更多数据
  /// [currentPageDataLength] 当前页数据长度
  /// [totalRecordsLength] 总记录数
  /// [pageSize] 每页大小
  /// 返回true表示还有更多数据，false表示没有更多数据
  bool hasMore(
      int currentPageDataLength, int totalRecordsLength, int pageSize) {
    // 默认逻辑：当前页数据完整且当前记录数小于总记录数
    return currentPageDataLength >= pageSize &&
        currentPageDataLength < totalRecordsLength;
  }

  /// 更新加载状态的方法
  /// [isLoading] 是否正在加载
  void curState(bool isLoading) {
    // 默认实现为空，业务端可以重写
  }

  /// 数据更新回调方法
  /// [records] 当前所有已加载的数据
  void onResultAllList(List<T> records) {
    // 默认实现为空，业务端可以重写
  }
}

/// 分页列表视图组件
class PaginationListView<T> extends StatefulWidget {
  /// 分页控制器
  final PaginationListController<T> controller;

  /// 每页大小，默认30
  final int pageSize;

  /// 滚动触发距离，默认200
  final double triggerDistance;

  /// 列表项构建器
  final Widget Function(BuildContext context, T item, int index) itemBuilder;

  /// 视图类型，默认ListView
  final PaginationViewType viewType;

  /// 网格布局配置（仅当viewType为GridView时有效）
  final PaginationGridConfig? gridConfig;

  /// 动态网格布局配置回调，可以根据index返回不同的配置
  final PaginationGridConfig Function(int index)? dynamicGridConfig;

  /// 加载指示器
  final Widget? loadingIndicator;

  /// 没有更多数据指示器
  final Widget? noMoreDataIndicator;

  /// 空数据指示器
  final Widget? emptyIndicator;

  /// 错误指示器
  final Widget Function(String? errorMessage, VoidCallback onRetry)?
      errorIndicator;

  /// 列表内边距
  final EdgeInsets padding;

  /// 是否支持下拉刷新
  final bool enableRefresh;

  /// 刷新回调
  final Future<void> Function()? onRefresh;

  ///列表上面的其他sliver
  final List<Widget>? topSlivers;

  /// 滚动物理特性，用于控制滑动行为
  final ScrollPhysics? physics;

  const PaginationListView({
    super.key,
    required this.controller,
    required this.itemBuilder,
    this.viewType = PaginationViewType.listView,
    this.gridConfig,
    this.dynamicGridConfig,
    this.pageSize = 30,
    this.triggerDistance = 200.0,
    this.loadingIndicator,
    this.noMoreDataIndicator,
    this.emptyIndicator,
    this.errorIndicator,
    this.padding = const EdgeInsets.all(16),
    this.enableRefresh = true,
    this.onRefresh,
    this.topSlivers,
    this.physics,
  });

  @override
  State<PaginationListView<T>> createState() => PaginationListViewState<T>();
}

class PaginationListViewState<T> extends State<PaginationListView<T>> {
  final ScrollController _scrollController = ScrollController();
  List<T> _records = [];
  bool _isLoading = false;
  bool _hasMore = true;
  int _currentPage = 1;
  int _totalRecords = 0;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
    _loadInitialData();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  /// 监听滚动事件
  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - widget.triggerDistance) {
      _loadMoreData();
    }
  }

  /// 加载初始数据
  Future<void> _loadInitialData() async {
    await _loadMoreData();
  }

  /// 加载更多数据
  Future<void> _loadMoreData() async {
    if (_isLoading || !_hasMore) return;

    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    // 通知控制器更新状态
    widget.controller.curState(_isLoading);

    try {
      print(
          'PaginationListView: 开始请求第 $_currentPage 页数据，每页 ${widget.pageSize} 条');

      // 调用业务端的loadDatas方法，直接获取数据
      final newData = await widget.controller
          .loadDatas(_currentPage, widget.pageSize, _hasMore);

      // 更新状态
      setState(() {
        _records.addAll(newData);
        _currentPage++;
        _totalRecords = _records.length; // 这里可以根据实际需要调整
        _hasMore = widget.controller
            .hasMore(newData.length, _totalRecords, widget.pageSize);
        _isLoading = false;
      });

      // 通知控制器更新状态和数据
      widget.controller.curState(_isLoading);
      widget.controller.onResultAllList(_records);

      print(
          'PaginationListView: ✅ 第 ${_currentPage - 1} 页数据加载成功，共 ${newData.length} 条记录，总记录数: ${_records.length}');
    } catch (e) {
      print('PaginationListView: ❌ 数据加载失败: $e');

      setState(() {
        _isLoading = false;
        _errorMessage = e.toString();
      });

      // 通知控制器更新状态
      widget.controller.curState(_isLoading);
    }
  }

  ///外部使用 强制重新加载
  Future<void> forceRefreshData() async {
    _refreshData();
  }

  ///外部使用 强制删除某个item
  Future<void> forceDeleteIndexFromList(int index) async {
    setState(() {
      _records.removeAt(index);
    });
  }

  /// 刷新数据
  Future<void> _refreshData() async {
    setState(() {
      _records.clear();
      _currentPage = 1;
      _hasMore = true;
      _totalRecords = 0;
      _errorMessage = null;
    });
    // 通知控制器数据已清空
    widget.controller.onResultAllList(_records);
    await _loadMoreData();
  }

  @override
  Widget build(BuildContext context) {
    return _buildContent();
  }

  /// 构建内容区域
  Widget _buildContent() {
    if (_errorMessage != null && _records.isEmpty) {
      if (widget.errorIndicator != null) {
        return widget.errorIndicator!(_errorMessage, _refreshData);
      }
      return _buildDefaultErrorIndicator();
    }

    if (_records.isEmpty && !_isLoading) {
      if (widget.emptyIndicator != null) {
        return widget.emptyIndicator!;
      }
      return _buildDefaultEmptyIndicator();
    }

    Widget scrollView = _buildScrollView();

    if (widget.enableRefresh) {
      return RefreshIndicator(
        onRefresh: widget.onRefresh ?? _refreshData,
        child: scrollView,
      );
    }

    return scrollView;
  }

  /// 构建滚动视图（ListView或GridView）
  Widget _buildScrollView() {
    if (widget.viewType == PaginationViewType.gridView) {
      return _buildGridView();
    } else {
      return _buildListView();
    }
  }

  /// 构建ListView
  Widget _buildListView() {
    final itemCount = _records.length +
        (_isLoading ? 1 : 0) +
        (!_hasMore && _records.isNotEmpty ? 1 : 0);

    return ListView.builder(
      controller: _scrollController,
      padding: widget.padding,
      physics: widget.physics,
      itemCount: itemCount,
      itemBuilder: (context, index) {
        if (index == _records.length) {
          if (_isLoading) {
            return widget.loadingIndicator ?? _buildDefaultLoadingIndicator();
          } else if (!_hasMore && _records.isNotEmpty) {
            return widget.noMoreDataIndicator ??
                _buildDefaultNoMoreDataIndicator();
          }
        }
        return widget.itemBuilder(context, _records[index], index);
      },
    );
  }

  /// 构建GridView
  Widget _buildGridView() {
    return CustomScrollView(
      controller: _scrollController,
      physics: widget.physics,
      slivers: [
        if (widget.topSlivers != null) ...widget.topSlivers!,
        // 网格内容
        SliverPadding(
          padding: widget.padding,
          sliver: SliverGrid(
            gridDelegate: _getGridDelegate(0), // 默认使用索引0的配置
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return widget.itemBuilder(context, _records[index], index);
              },
              childCount: _records.length,
            ),
          ),
        ),

        // 状态指示器（撑满一行）
        if (_isLoading)
          SliverToBoxAdapter(
            child: widget.loadingIndicator ?? _buildDefaultLoadingIndicator(),
          ),

        if (!_hasMore && _records.isNotEmpty)
          SliverToBoxAdapter(
            child: widget.noMoreDataIndicator ??
                _buildDefaultNoMoreDataIndicator(),
          ),
      ],
    );
  }
  
  /// 获取网格代理配置
  SliverGridDelegate _getGridDelegate(int index) {
    // 如果有动态配置回调，使用动态配置
    if (widget.dynamicGridConfig != null) {
      final config = widget.dynamicGridConfig!(index);
      return config.gridDelegate;
    }
    
    // 否则使用静态配置
    final gridConfig = widget.gridConfig ?? const PaginationGridConfig();
    return gridConfig.gridDelegate;
  }

  /// 构建默认加载指示器
  Widget _buildDefaultLoadingIndicator() {
    return const Padding(
      padding: EdgeInsets.all(16),
      child: Center(
        child: CircularProgressIndicator(
          color: Colors.white,
        ),
      ),
    );
  }

  /// 构建默认没有更多数据指示器
  Widget _buildDefaultNoMoreDataIndicator() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Center(
        child: Text(
          '已加载全部数据 (共$_totalRecords条)',
          style: const TextStyle(
            color: Colors.white70,
            fontSize: 14,
          ),
        ),
      ),
    );
  }

  /// 构建默认空数据指示器
  Widget _buildDefaultEmptyIndicator() {
    return const DefaultEmptyIndicator();
  }

  /// 构建默认错误指示器
  Widget _buildDefaultErrorIndicator() {
    return DefaultErrorIndicator(
      errorMessage: _errorMessage!,
      onRefreshTap: _refreshData,
    );
  }
}
